package org.ourguy.mymoviesandshows.datamodel;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class CoverArtFromURL implements ICoverArt, Serializable{

	private java.net.URL externalLink;
	private byte[] tumbnail;
	private int size;

	private static final long serialVersionUID = 1L;

	public CoverArtFromURL(String url) throws MalformedURLException {
		externalLink =  new URL(url);
	}

	public void makeThumbnail() throws IOException {
		HttpURLConnection conn = 
				(HttpURLConnection) externalLink.openConnection();
		conn.setDoInput(true);
		conn.connect();
		InputStream is = conn.getInputStream();
		
		Bitmap image = BitmapFactory.decodeStream(is);
		image = Bitmap.createScaledBitmap(image, 64,
						(int)((64* image.getHeight()/image.getWidth())), true);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
		size = stream.size();
		tumbnail = stream.toByteArray();
	}
	
	public Bitmap getThumbnail() {
		if (size == 0) {
			try {
				makeThumbnail();
			} catch (IOException e) {
				return null;
			}
		}
		return BitmapFactory.decodeByteArray(tumbnail, 0, size);
	}

	public Bitmap loadInImageView(int width) {
		try {
			HttpURLConnection conn = (HttpURLConnection) externalLink.openConnection();
			conn.setDoInput(true);
			conn.connect();
			InputStream is = conn.getInputStream();
			Bitmap image = BitmapFactory.decodeStream(is);
			image = Bitmap.createScaledBitmap(image, width,
							(int)((width* image.getHeight()/image.getWidth())), true);
			return image;
		} catch (Exception e) {
			return null;
		}
		
	}
}
